package com.camel.docker.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.camel.core.utils.PaginationUtil;
import com.camel.docker.entity.Project;
import com.camel.docker.mapper.ContainerMapper;
import com.camel.docker.service.ContainerService;
import com.camel.docker.service.DockerClientService;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Container;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author baily
 * @since 2020-10-16
 */
@Service
public class ContainerServiceImpl extends ServiceImpl<ContainerMapper, Project> implements ContainerService {

    @Autowired
    private ContainerMapper mapper;

    @Autowired
    private DockerClientService dockerClientService;

    @Override
    public PageInfo<Project> selectPage(Project entity) {
        PageInfo pageInfo = PaginationUtil.startPage(entity, () -> {
            mapper.list(entity);
        });
        DockerClient client = dockerClientService.connect();
        for (Object c: pageInfo.getList()) {
            Project container = (Project) c;
            Map<String, String> labels = new HashMap<>();
            labels.put("pname", container.getName());
            List<Container> containers = client.listContainersCmd().withLabelFilter(labels).exec();
            container.setContainers(containers);
        }
        return pageInfo;
    }
}
